import { useEffect, useState } from 'react';
import { Table, Button, Space, Tag, Typography, Modal, App, Form } from 'antd';
import { getElements, deleteElement, getElementById, addElement, updateElement } from '@/api/element';
import { 
  PlusOutlined, 
  EditOutlined, 
  DeleteOutlined
} from '@ant-design/icons';
import DynamicIcon from '@/components/common/DynamicIcon';
import ElementForm from './ElementForm';
import AuthControl from '@/components/common/AuthControl';
import hasElementAuth from '@/utils/auth';

const { Text } = Typography;
const ElementIndex = () => {
  const [elements, setElements] = useState([]);
  const [loading, setLoading] = useState(false);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [isEditing, setIsEditing] = useState(false);
  const [isAddChild, setIsAddChild] = useState(false);
  const [form] = Form.useForm();
  const { modal,message } = App.useApp();


  useEffect(() => {
    loadElements();
  }, []);

  const loadElements = () => {
    setLoading(true);
    getElements({}).then(res => {
      if (res.data) {
        setElements(res.data);
      }
    }).finally(() => {
      setLoading(false);
    })
  };

  const handleAdd = (record) => {
    setIsEditing(false);
    setIsModalVisible(true);
    form.resetFields();
    if (record) {
      setIsAddChild(true);
      form.setFieldsValue({
        parentId: record.elementId
      });
    }
  };

  const handleEdit = (record) => {
    setIsEditing(true);
    getElementById(record.elementId).then(res => {
      if (res.data) {
        const formData = {
          ...res.data
        };
        if((res.data.component&&res.data.component!="")||(res.data.isLink&&res.data.isLink!="")){
          formData.isPage = true
          if(res.data.component&&res.data.component!=""){
            formData.isComponent = true
          }else{
            formData.isComponent = false
          }
        }else{
          formData.isPage = false
        }
        form.setFieldsValue(formData);
        setIsModalVisible(true);
      }
    });
  };

  const handleDelete = (id) => {
    modal.confirm({
      title: '确认删除',
      content: '确定要删除这个元素吗？',
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        setLoading(true);
        deleteElement(id).then(() => {
          message.success("元素已删除");
          loadElements();
        })
          .finally(() => {
            setLoading(false);
          });
      }
    });
  };

  const handleFormCancel = () => {
    setIsModalVisible(false);
    form.resetFields();
  };

  const handleFormConfirm = () => {
    form.validateFields().then((values) => {
        const submitValues = {
          ...values,
          affix: values.isAffix,
        };

        const apiCall = isEditing ? updateElement : addElement;
        
        apiCall(submitValues).then(() => {
          message.success(isEditing ? "编辑成功！" : "添加成功！");
          setIsModalVisible(false);
          form.resetFields();
          loadElements();
        });
      })
  };
  const getColumns = () => {
    const columns = [
      {
        title: '菜单名称',
        dataIndex: 'title',
        key: 'title',
        render: (text, record) => (
          <Space>
            <DynamicIcon iconName={record.icon}></DynamicIcon>
            <span>{text}</span>
          </Space>
        )
      },
      {
        title: '路径/code',
        dataIndex: 'path',
        key: 'path',
        render: (text, record) => {
          return (
            <Space>
              <Text>{text}</Text>
              <Text>{record.code}</Text>
            </Space>
          );
        }
      },
      {
        title: '类型',
        dataIndex: 'typeName',
        key: 'typeName',
        render: (text, record) => (
          <Tag color={record.type === '0' ? 'blue' : 'green'}>
            {text || '未知'}
          </Tag>
        )
      }
    ]

    if (hasElementAuth(['edit', 'delete','add'])) {
      columns.push(
        {
          title: '操作',
          key: 'action',
          width: 300,
          align: 'right',
          render: (_, record) => (
            <Space>
              <AuthControl permission="add">
                {record.type === '0' && (
                  <Button
                    icon={<PlusOutlined />}
                    onClick={() => handleAdd(record)}
                  >
                    添加子菜单
                  </Button>
                )}
              </AuthControl>
              <AuthControl permission="edit">
                <Button
                  icon={<EditOutlined />}
                  onClick={() => handleEdit(record)}
                >
                  编辑
                </Button>
              </AuthControl>
              <AuthControl permission="delete">
                <Button
                  danger
                  icon={<DeleteOutlined />}
                  onClick={() => handleDelete(record.elementId)}
                >
                  删除
                </Button>
              </AuthControl>
            </Space>
          ),
        },
      )
    }
    return columns;
  };



  return (
    <div style={{ padding: '20px' }}>
      <AuthControl permission="add">
        <Button loading={loading} type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
          新增菜单
        </Button>
      </AuthControl>
      
      <Table
        columns={getColumns()}
        dataSource={elements}
        loading={loading}
        rowKey="elementId"
        pagination={false}
        style={{marginTop:16}}
      />
      
      <Modal
        title={isEditing ? '编辑元素' : '新增元素'}
        width={720}
        open={isModalVisible}
        onCancel={handleFormCancel}
        onOk={handleFormConfirm}
        destroyOnHidden={true}
      >
        <ElementForm 
          form={form}
          isEditing={isEditing}
          isAddChild={isAddChild}
        />
      </Modal>
    </div>
  );
};

export default ElementIndex;